from src.model.AViewModel import AViewModel
from src.model.ALikeModel import ALikeModel
from src.init.init_db import db


class AViewTool:
    # 添加或更新浏览记录
    def add_view(self, aid: int, uid: int):
        # 查询是否已有该用户对该文章的浏览记录
        aview = AViewModel.query.filter_by(aid=aid, uid=uid).first()
        if aview is None:
            # 没有记录则新建，初始 count 为 1
            aview = AViewModel(aid=aid, uid=uid, count=1)
            db.session.add(aview)
        else:
            # 已有记录则 count 自增
            aview.count = aview.count + 1
        db.session.commit()  # 提交事务

    # 查询用户浏览记录，并按浏览次数降序排列
    def check_view(self, uid):
        aviews = AViewModel.query.filter_by(uid=uid).order_by(AViewModel.count.desc()).all()
        result = [
            {
                "aid": aview.aid,
                "count": aview.count
            }
            for aview in aviews
        ]
        return result

    def check_like(self, uid):
        alikes = ALikeModel.query.filter_by(uid=uid)
        result = [
            alike.aid
            for alike in alikes
        ]
        return result

    # 删除该用户的所有浏览记录
    def delete_user_view(self, uid):
        aviews = AViewModel.query.filter_by(uid=uid).all()

        for aview in aviews:
            db.session.delete(aview)

        db.session.commit()

    def delete_article_view(self, aid):
        aviews = AViewModel.query.filter_by(aid=aid).all()

        for aview in aviews:
            db.session.delete(aview)

        db.session.commit()
